package com.example.mydy;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.mydy.adapter.WithdrawalRequestAdapter;
import com.example.mydy.model.WithdrawalRequest;
import com.example.mydy.utils.WithdrawalService;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class WithdrawalManagementActivity extends AppCompatActivity implements WithdrawalRequestAdapter.OnItemClickListener {

    private TextView tvNoSelection, tvUserNickname, tvWithdrawalAmount, tvUserName, tvAlipayAccount, tvRequestTime, tvWithdrawalStatus;
    private Button btnApprove, btnReject, btnRefresh, navHome, logoutButton;
    private ImageView ivUserAvatar;
    private EditText etRemark;
    private Spinner spinnerStatus;
    private RecyclerView rvWithdrawalRequests;
    private LinearLayout containerRequestDetails;

    private WithdrawalRequestAdapter adapter;
    private List<WithdrawalRequest> withdrawalRequests = new ArrayList<>();
    private WithdrawalRequest selectedRequest = null;
    private WithdrawalService withdrawalService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_withdrawal_management);

        // 初始化服务
        withdrawalService = WithdrawalService.getInstance(this);
        withdrawalService.addMockData(); // 添加一些模拟数据

        // 初始化视图
        initViews();
        setupSpinner();
        setupRecyclerView();
        
        // 设置点击事件
        setupClickListeners();
        
        // 加载提现请求
        loadWithdrawalRequests();
    }

    private void initViews() {
        ivUserAvatar = findViewById(R.id.iv_user_avatar);
        tvUserNickname = findViewById(R.id.tv_user_nickname);
        tvWithdrawalAmount = findViewById(R.id.tv_withdrawal_amount);
        tvUserName = findViewById(R.id.tv_user_name);
        tvAlipayAccount = findViewById(R.id.tv_alipay_account);
        tvRequestTime = findViewById(R.id.tv_request_time);
        tvWithdrawalStatus = findViewById(R.id.tv_withdrawal_status);
        tvNoSelection = findViewById(R.id.tv_no_selection);
        containerRequestDetails = findViewById(R.id.container_request_details);
        
        btnApprove = findViewById(R.id.btn_approve);
        btnReject = findViewById(R.id.btn_reject);
        btnRefresh = findViewById(R.id.btn_refresh);
        navHome = findViewById(R.id.withdrawal_nav_home);
        logoutButton = findViewById(R.id.logout_button);
        
        etRemark = findViewById(R.id.et_remark);
        spinnerStatus = findViewById(R.id.spinner_status);
        rvWithdrawalRequests = findViewById(R.id.rv_withdrawal_requests);
    }

    private void setupSpinner() {
        // 设置状态筛选下拉列表
        String[] statusOptions = {"全部", "待处理", "已通过", "已拒绝"};
        ArrayAdapter<String> adapter = new ArrayAdapter<>(
                this, android.R.layout.simple_spinner_item, statusOptions);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerStatus.setAdapter(adapter);
        
        spinnerStatus.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selectedStatus;
                switch (position) {
                    case 1:
                        selectedStatus = WithdrawalRequest.STATUS_PENDING;
                        break;
                    case 2:
                        selectedStatus = WithdrawalRequest.STATUS_APPROVED;
                        break;
                    case 3:
                        selectedStatus = WithdrawalRequest.STATUS_REJECTED;
                        break;
                    default:
                        selectedStatus = "ALL";
                        break;
                }
                loadWithdrawalRequests(selectedStatus);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                loadWithdrawalRequests("ALL");
            }
        });
    }

    private void setupRecyclerView() {
        // 设置提现请求列表
        adapter = new WithdrawalRequestAdapter(this, withdrawalRequests, this);
        rvWithdrawalRequests.setLayoutManager(new LinearLayoutManager(this));
        rvWithdrawalRequests.setAdapter(adapter);
    }

    private void setupClickListeners() {
        // 设置导航按钮点击事件
        navHome.setOnClickListener(v -> {
            Intent intent = new Intent(WithdrawalManagementActivity.this, AdminActivity.class);
            startActivity(intent);
            finish();
        });

        // 设置退出按钮点击事件
        logoutButton.setOnClickListener(v -> {
            Toast.makeText(WithdrawalManagementActivity.this, "退出账户", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(WithdrawalManagementActivity.this, LoginActivity.class);
            startActivity(intent);
            finish();
        });

        // 设置刷新按钮点击事件
        btnRefresh.setOnClickListener(v -> {
            String status = getCurrentSelectedStatus();
            loadWithdrawalRequests(status);
        });

        // 设置通过按钮点击事件
        btnApprove.setOnClickListener(v -> {
            if (selectedRequest == null) {
                Toast.makeText(this, "请先选择一个提现申请", Toast.LENGTH_SHORT).show();
                return;
            }
            
            // 只允许处理待处理状态的申请
            if (!WithdrawalRequest.STATUS_PENDING.equals(selectedRequest.getStatus())) {
                Toast.makeText(this, "只能处理待处理状态的申请", Toast.LENGTH_SHORT).show();
                return;
            }
            
            // 获取备注
            String remark = etRemark.getText().toString().trim();
            
            // 确认对话框
            new AlertDialog.Builder(this)
                .setTitle("确认通过")
                .setMessage("确定要通过此提现申请吗？用户将从余额中扣除 ¥" + String.format(Locale.getDefault(), "%.2f", selectedRequest.getAmount()))
                .setPositiveButton("确定", (dialog, which) -> {
                    approveWithdrawal(remark);
                })
                .setNegativeButton("取消", null)
                .show();
        });

        // 设置拒绝按钮点击事件
        btnReject.setOnClickListener(v -> {
            if (selectedRequest == null) {
                Toast.makeText(this, "请先选择一个提现申请", Toast.LENGTH_SHORT).show();
                return;
            }
            
            // 只允许处理待处理状态的申请
            if (!WithdrawalRequest.STATUS_PENDING.equals(selectedRequest.getStatus())) {
                Toast.makeText(this, "只能处理待处理状态的申请", Toast.LENGTH_SHORT).show();
                return;
            }
            
            // 获取备注（拒绝原因）
            String remark = etRemark.getText().toString().trim();
            if (TextUtils.isEmpty(remark)) {
                Toast.makeText(this, "请输入拒绝原因", Toast.LENGTH_SHORT).show();
                return;
            }
            
            // 确认对话框
            new AlertDialog.Builder(this)
                .setTitle("确认拒绝")
                .setMessage("确定要拒绝此提现申请吗？")
                .setPositiveButton("确定", (dialog, which) -> {
                    rejectWithdrawal(remark);
                })
                .setNegativeButton("取消", null)
                .show();
        });
    }

    private String getCurrentSelectedStatus() {
        int position = spinnerStatus.getSelectedItemPosition();
        switch (position) {
            case 1:
                return WithdrawalRequest.STATUS_PENDING;
            case 2:
                return WithdrawalRequest.STATUS_APPROVED;
            case 3:
                return WithdrawalRequest.STATUS_REJECTED;
            default:
                return "ALL";
        }
    }

    private void loadWithdrawalRequests() {
        loadWithdrawalRequests("ALL");
    }

    private void loadWithdrawalRequests(String status) {
        // 显示加载中
        Toast.makeText(this, "正在加载...", Toast.LENGTH_SHORT).show();
        
        // 根据状态加载提现申请
        withdrawalService.getWithdrawalsByStatus(status, new WithdrawalService.WithdrawalListCallback() {
            @Override
            public void onSuccess(List<WithdrawalRequest> withdrawals) {
                withdrawalRequests.clear();
                withdrawalRequests.addAll(withdrawals);
                adapter.updateData(withdrawals);
                
                // 清除选中状态
                clearSelection();
            }

            @Override
            public void onFailure(String message) {
                Toast.makeText(WithdrawalManagementActivity.this, "加载失败: " + message, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void approveWithdrawal(String remark) {
        if (selectedRequest == null) return;
        
        // 显示处理中对话框
        AlertDialog processingDialog = new AlertDialog.Builder(this)
            .setTitle("处理中")
            .setMessage("正在处理申请...")
            .setCancelable(false)
            .create();
        processingDialog.show();
        
        // 调用服务处理提现
        withdrawalService.approveWithdrawal(selectedRequest, remark, new WithdrawalService.WithdrawalCallback() {
            @Override
            public void onSuccess() {
                processingDialog.dismiss();
                Toast.makeText(WithdrawalManagementActivity.this, "提现申请已通过", Toast.LENGTH_SHORT).show();
                
                // 更新请求状态
                tvWithdrawalStatus.setText("状态: 已通过");
                selectedRequest.setStatus(WithdrawalRequest.STATUS_APPROVED);
                
                // 刷新列表
                loadWithdrawalRequests(getCurrentSelectedStatus());
            }

            @Override
            public void onFailure(String message) {
                processingDialog.dismiss();
                Toast.makeText(WithdrawalManagementActivity.this, "处理失败: " + message, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void rejectWithdrawal(String remark) {
        if (selectedRequest == null) return;
        
        // 显示处理中对话框
        AlertDialog processingDialog = new AlertDialog.Builder(this)
            .setTitle("处理中")
            .setMessage("正在处理申请...")
            .setCancelable(false)
            .create();
        processingDialog.show();
        
        // 调用服务处理提现
        withdrawalService.rejectWithdrawal(selectedRequest, remark, new WithdrawalService.WithdrawalCallback() {
            @Override
            public void onSuccess() {
                processingDialog.dismiss();
                Toast.makeText(WithdrawalManagementActivity.this, "提现申请已拒绝", Toast.LENGTH_SHORT).show();
                
                // 更新请求状态
                tvWithdrawalStatus.setText("状态: 已拒绝");
                selectedRequest.setStatus(WithdrawalRequest.STATUS_REJECTED);
                
                // 刷新列表
                loadWithdrawalRequests(getCurrentSelectedStatus());
            }

            @Override
            public void onFailure(String message) {
                processingDialog.dismiss();
                Toast.makeText(WithdrawalManagementActivity.this, "处理失败: " + message, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void clearSelection() {
        selectedRequest = null;
        containerRequestDetails.setVisibility(View.GONE);
        tvNoSelection.setVisibility(View.VISIBLE);
    }

    @Override
    public void onItemClick(WithdrawalRequest request, int position) {
        // 保存选中的请求
        selectedRequest = request;
        
        // 显示详细信息，隐藏提示文本
        containerRequestDetails.setVisibility(View.VISIBLE);
        tvNoSelection.setVisibility(View.GONE);
        
        // 填充详细信息
        tvUserNickname.setText(request.getUserNickname());
        tvWithdrawalAmount.setText(String.format(Locale.getDefault(), "提现金额: ¥%.2f", request.getAmount()));
        tvUserName.setText("姓名: " + request.getRealName());
        tvAlipayAccount.setText("支付宝账号: " + request.getAlipayAccount());
        
        // 格式化请求时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        tvRequestTime.setText("申请时间: " + sdf.format(request.getRequestTime()));
        
        // 根据状态设置状态文本
        String statusText;
        switch (request.getStatus()) {
            case WithdrawalRequest.STATUS_APPROVED:
                statusText = "已通过";
                break;
            case WithdrawalRequest.STATUS_REJECTED:
                statusText = "已拒绝";
                break;
            default:
                statusText = "待处理";
                break;
        }
        tvWithdrawalStatus.setText("状态: " + statusText);
        
        // 根据状态启用或禁用按钮
        boolean isPending = WithdrawalRequest.STATUS_PENDING.equals(request.getStatus());
        btnApprove.setEnabled(isPending);
        btnReject.setEnabled(isPending);
        
        // 如果已处理，显示处理备注
        if (!isPending && request.getRemark() != null) {
            etRemark.setText(request.getRemark());
            etRemark.setEnabled(false);
        } else {
            etRemark.setText("");
            etRemark.setEnabled(true);
        }
    }
}